import { store } from "@/stores";
import { defineStore } from "pinia";
import type { CanvasState, Canvas, CanvasData } from "./helper";
import {
  defaultSetting,
  getLocalState,
  removeLocalState,
  setLocalState,
} from "./helper";
import useCanvas from "@/hooks/canvas/useCanvas";
import { useKBStoreHook } from "../KB/index";
import { useSelectGraphStoreHook } from "../selectGraph";

export const useCanvasStore = defineStore("canvas-storage", {
  state: (): CanvasState => getLocalState(),
  getters: {
    getEdgesByNum(state) {
      return (isSelect?: boolean) => {
        const useSelectGraphStore = useSelectGraphStoreHook();
        let data = {
          nodes: [],
          edges: [],
        };
        if (useSelectGraphStore.selectCanvas && !isSelect) {
          data = useSelectGraphStore.selectCanvas;
        } else {
          const uuid = state.active;
          const canvas = state.canvas.find((item) => item.uuid === uuid);
          data = JSON.parse(JSON.stringify(canvas.data));
        }
        const { edges } = data;
        const useKBStore = useKBStoreHook();
        const tagEdges = JSON.parse(JSON.stringify(useKBStore.tagEdges));
        const useTagsEdgEs = tagEdges.filter(
          (item) => edges.findIndex((ele) => item.code === ele.edgeName) > -1
        );
        useTagsEdgEs.forEach((item) => {
          item.children = [];
          edges.forEach((ele) => {
            if (item.code === ele.edgeName) {
              item.children.push(ele);
            }
          });
        });
        return useTagsEdgEs;
      };
    },

    // 右侧抽屉统计使用
    getStatistics(state) {
      return (isSelect?: boolean) => {
        const useSelectGraphStore = useSelectGraphStoreHook();
        let data = {
          nodes: [],
          edges: [],
        };
        if (useSelectGraphStore.selectCanvas && !isSelect) {
          data.nodes = useSelectGraphStore.selectCanvas.nodes;
          data.edges = this.getCanvasByData().edges;
        } else {
          const uuid = state.active;
          const canvas = state.canvas.find((item) => item.uuid === uuid);
          data = JSON.parse(JSON.stringify(canvas.data));
        }
        const { nodes, edges } = data;

        const useKBStore = useKBStoreHook(); // tags
        const tags = JSON.parse(JSON.stringify(useKBStore.tags));
        const useTags = tags.filter(
          (item) => nodes.findIndex((ele) => ele.tageName === item.code) > -1
        );
        console.log(tags, useTags, "useTags");
        useTags.forEach((item) => {
          item.children = [];
          nodes.forEach((ele) => {
            ele.tags.forEach((i) => {
              if (i.name === item.code) {
                ele.properties = i.properties;
              }
            });
            if (ele.tageName === item.code) {
              item.children.push(ele);
            }
            const edgesIds = edges
              .map((k) => {
                if (k.srcID === ele.id) {
                  return k.dstID;
                }
                if (k.dstID === ele.id) {
                  return k.srcID;
                }
                return false;
              })
              .filter((k) => k);
            ele.edges = Array.from(new Set(edgesIds));
          });
        });
        return useTags;
      };
    },

    getNodesItem(state) {
      return (id, key) => {
        const uuid = state.active;
        const canvas = state.canvas.find((item) => item.uuid === uuid);
        const { nodes } = canvas.data;
        const item = nodes.find((item) => item.id === id);
        // console.log(id, item, nodes, "getNodesItem");
        return item ? item[key] : "";
      };
    },

    // 获取整个canvas数据 actionBar组件使用
    getCanvas(state) {
      return (canvasUuid?: string) => {
        const uuid = canvasUuid ?? state.active;
        const canvas = state.canvas.find((item) => item.uuid === uuid);
        return canvas;
      };
    },

    // 获取当前画布id。canvasG6使用
    getCanvasById(state) {
      return (canvasUuid?: string) => {
        const uuid = canvasUuid ?? state.active;
        const canvas = state.canvas.find((item) => item.uuid === uuid);
        if (canvas) {
          return canvas.id ?? "";
        }
        return "";
      };
    },

    // 获取当前画布文件名，canvasG6使用
    getCanvasByName(state) {
      return (canvasUuid?: string) => {
        if (canvasUuid)
          return (
            state.canvas.find((item) => item.uuid === canvasUuid).name ?? ""
          );
        return (
          state.canvas.find((item) => item.uuid === state.active).name ?? ""
        );
      };
    },

    // 获取当前画布数据。canvasG6 和 relationDialog 组件使用
    getCanvasByData(state) {
      const data: CanvasData = {
        nodes: [],
        edges: [],
      };
      return (canvasUuid?: string): CanvasData => {
        if (canvasUuid)
          return (
            state.canvas.find((item) => item.uuid === canvasUuid).data ?? data
          );
        return (
          state.canvas.find((item) => item.uuid === state.active).data ?? data
        );
      };
    },
  },
  actions: {
    setCanvasId(oldId, uuid) {
      const canvas = this.canvas.find((item) => item.uuid === oldId);
      canvas.uuid = uuid;
      canvas.id = uuid;
      this.active = uuid;
      this.recordState();
    },

    setCanvasData(data) {
      const canvas = this.canvas.find((item) => item.uuid === this.active);
      canvas.data = useCanvas(data, canvas.data);
      this.recordState();
    },

    setCanvasEdges(edges) {
      const canvas = this.canvas.find((item) => item.uuid === this.active);
      canvas.data.edges = edges;
      this.recordState();
    },

    setCanvas(dara) {
      const canvas = this.canvas.find((item) => item.uuid === this.active);
      canvas.data = dara;
      this.recordState();
    },

    openCanvas(uuid: string) {
      this.active = uuid;
      this.recordState();
    },

    delCanvas(uuid) {
      const findIndex = this.canvas.findIndex((item) => item.uuid === uuid);
      this.canvas.splice(findIndex, 1);
      if (this.canvas.length === 0) {
        this.active = null;
        this.recordState();
        return;
      }
      if (findIndex === 0) {
        this.active = this.canvas[0].uuid;
      } else {
        this.active = this.canvas[findIndex - 1].uuid;
      }

      this.recordState();
    },

    closeCanvas(index: number) {
      this.canvas.splice(index, 1);
      if (this.canvas.length === 0) {
        this.active = null;
        this.recordState();
        return;
      }
      const findindex = this.canvas.findIndex(
        (item) => item.uuid === this.active
      );
      if (findindex === -1) {
        // 不存在，已被删除
        if (index === 0) {
          this.active = this.canvas[0].uuid;
        } else {
          this.active = this.canvas[index - 1].uuid;
        }
      }

      this.recordState();
    },

    pushCanvas(canvasItem: Canvas) {
      const findIndex = this.canvas.findIndex(
        (item) => item.uuid === canvasItem.uuid
      );
      this.active = canvasItem.uuid;
      if (findIndex > -1) {
        this.canvas[findIndex] = {
          ...canvasItem,
        };
        this.recordState();
        return;
      }
      this.canvas.push(canvasItem);
      this.recordState();
    },

    updateCanvas(canvas: Partial<CanvasState>) {
      this.$state = { ...this.$state, ...canvas };
      this.recordState();
    },

    closeAllCanvas() {
      this.canvas = [];
      this.recordState();
    },

    resetDrawer() {
      this.$state = defaultSetting();
      removeLocalState();
    },

    recordState() {
      setLocalState(this.$state);
    },
  },
});

export function useCanvasStoreHook() {
  return useCanvasStore(store);
}
